import tkinter as tk
from tkinter import messagebox, ttk
import csv
import redis
import json
import openai
import time
from threading import Thread
import json
import openai
from config import OPENAI_API_KEY, OPENAI_API_BASE

openai.api_key = OPENAI_API_KEY
openai.api_base = OPENAI_API_BASE

class StudentManager(object):
    def __init__(self, master=None):
        self.root = master
        self.root.title('学生成绩管理系统 - 教师端')
        
        # 设置全屏
        self.root.attributes('-fullscreen', True)
        self.root.configure(bg='#121212')
        
        # 添加ESC键退出全屏的功能
        self.root.bind('<Escape>', lambda e: self.root.attributes('-fullscreen', False))
        
        # 设置样式
        self.style = ttk.Style()
        self.style.configure('Custom.TButton',
                            font=('微软雅黑', 12),
                            padding=5)
        
        # 初始化数据和状态
        self.data = {}
        self.status_acq = self.status_a = self.status_b = self.status_c = self.status_d = self.status_e = 0
        # 连接 Redis 数据库
        self.db2 = redis.Redis(host='127.0.0.1', port=6379, db=3, decode_responses=True)
        self.db0 = redis.Redis(host='127.0.0.1', port=6379, db=1, decode_responses=True)
        self.db1 = redis.Redis(host='127.0.0.1', port=6379, db=2, decode_responses=True)
        # 初始化加载数据
        self.data0 = self.db0.hgetall('student')
        # self.data2 = self.db2.hgetall('student') # db2 主要用于旧的学生端，如果只保留教师端可以考虑移除
        
        # 创建主框架
        self.main_frame = tk.Frame(self.root, bg='#121212')
        self.main_frame.pack(expand=True, fill='both', padx=30, pady=30)
        
        # 标题区域
        title_frame = tk.Frame(self.main_frame, bg='#121212')
        title_frame.pack(pady=20)
        
        title_label = tk.Label(title_frame,
                              text='学生成绩管理系统',
                              font=('微软雅黑', 32, 'bold'),
                              bg='#121212',
                              fg='#00bcd4')
        title_label.pack()
        
        subtitle_label = tk.Label(title_frame,
                                text='STUDENT DATA MANAGEMENT',
                                font=('Consolas', 14),
                                bg='#121212',
                                fg='#607d8b')
        subtitle_label.pack(pady=5)
        
        # 输入区域框架
        input_frame = tk.Frame(self.main_frame, bg='#1e1e1e', bd=2, relief='flat', highlightthickness=1, highlightbackground='#37474f')
        input_frame.pack(fill='x', pady=20, padx=20)
        
        # 输入框和标签数据
        fields = [
            ('学号', 'entry5', 0), ('月份(1-12)', 'entry6', 1), ('姓名', 'entry1', 2),
            ('语文', 'entry2', 3), ('数学', 'entry3', 4), ('英语', 'entry4', 5),
            ('物理', 'entry7', 6), ('化学', 'entry8', 7), ('生物', 'entry9', 8)
        ]
        
        # 创建输入框和标签
        for label_text, entry_name, col in fields:
            frame = tk.Frame(input_frame, bg='#1e1e1e')
            frame.grid(row=0, column=col, padx=8, pady=8, sticky='w')
            
            tk.Label(frame,
                    text=label_text,
                    font=('微软雅黑', 10, 'bold'),
                    bg='#1e1e1e',
                    fg='#b0bec5').pack(anchor='w')
            
            entry = tk.Entry(frame,
                            font=('Consolas', 10),
                            width=10,
                            bg='#263238',
                            fg='#00bcd4',
                            insertbackground='#00bcd4',
                            relief='flat',
                            highlightthickness=1,
                            highlightbackground='#37474f',
                            highlightcolor='#00bcd4')
            entry.pack(anchor='w')
            setattr(self, entry_name, entry)
        
        # 确认按钮
        confirm_button = tk.Button(input_frame,
                                 text='信息确定',
                                 font=('微软雅黑', 12, 'bold'),
                                 bg='#00bcd4',
                                 fg='#121212',
                                 activebackground='#00838f',
                                 activeforeground='#ffffff',
                                 relief='flat',
                                 padx=10,
                                 pady=5,
                                 command=self.check1)
        confirm_button.grid(row=0, column=len(fields), padx=8, pady=8, sticky='e')
        
        # 数据显示区域框架
        data_frame = tk.Frame(self.main_frame, bg='#1e1e1e', bd=2, relief='flat', highlightthickness=1, highlightbackground='#37474f')
        data_frame.pack(fill='both', expand=True, pady=20, padx=20)
        
        self.studentdata = tk.Text(data_frame,
                                 font=('Consolas', 12),
                                 bg='#263238',
                                 fg='#00bcd4',
                                 insertbackground='#00bcd4',
                                 relief='flat',
                                 highlightthickness=0)
        self.studentdata.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 按钮区域框架
        button_frame = tk.Frame(self.main_frame, bg='#121212')
        button_frame.pack(fill='x', pady=10, padx=20)
        
        buttons = [
            ('启动系统', self.get_next1, '#ff9800'),
            ('新建学生', self.create_data, '#4caf50'),
            ('显示全部', self.show_data, '#2196f3'),
            ('查询信息', self.acquire_data, '#9c27b0'),
            ('删除信息', self.delete_data, '#f44336'),
            ('修改信息', self.modify_data, '#ffc107'),
            ('AI分析', self.ai_analysis, '#00acc1'),
            ('退出系统', self.quit, '#607d8b')
        ]
        
        for i, (text, command, color) in enumerate(buttons):
            btn = tk.Button(button_frame,
                           text=text,
                           font=('微软雅黑', 12, 'bold'),
                           bg=color,
                           fg='#121212',
                           activebackground=color,
                           activeforeground='#ffffff',
                           relief='flat',
                           padx=15,
                           pady=8,
                           command=command)
            btn.grid(row=0, column=i, padx=5, sticky='ew')
        
        for i in range(len(buttons)):
            button_frame.grid_columnconfigure(i, weight=1)
        
        self.root.mainloop()

    def get_next1(self):
        #清空显示
        self.studentdata.delete('1.0', 'end')
        self.str1 = """
        ****************************
        欢迎使用【学生信息管理系统】V1.0
          请从右侧选择你想要进行的操作
                新建学生信息
                显示全部信息
                查询学生信息
                删除学生信息
                修改学生信息
                退出学生系统
        ****************************
        """
        self.studentdata.insert(tk.END, self.str1)

    def get_next2(self):
        self.studentdata.delete('1.0', 'end')
        self.str2 = """
        ==========================
         请从输入框输入要增加的学生的
         学号，月份，姓名，语文，数学，英语，
         物理，化学，生物成绩
        ==========================
        全部填写完按右侧的---信息确认
        ==========================
        """
        self.studentdata.insert(tk.END, self.str2)
        self.status_a = 1

    def check(self):
        messagebox.showinfo('提示', '一定要合法输入，否则文件保存会出错哦')

    def check1(self):
        if self.status_acq:
            self.status_acq = 0
            name = self.entry1.get().strip()
            schoolnumber = self.entry5.get().strip()
            try:
                month = int(self.entry6.get().strip() or '0')
            except ValueError:
                month = 0

            self.studentdata.delete('1.0', 'end')
            self.studentdata.insert(tk.END, '查询结果如下：\n', 'info_tag')
            self.studentdata.tag_config('info_tag', foreground='#00bcd4')

            header = "学号\t姓名\t语文\t数学\t英语\t物理\t化学\t生物\t总分\t月份\n"
            self.studentdata.insert(tk.END, header, 'header_tag')
            self.studentdata.tag_config('header_tag', foreground='#81d4fa', font=('Consolas', 12, 'bold'))

            found = False
            try:
                for key, value in self.data0.items():
                    try:
                        data = json.loads(value)
                        # 从键中提取学号和月份
                        if '_' in key:
                            key_schoolnumber, key_month = key.split('_')
                        else:
                            # 处理旧数据格式
                            key_schoolnumber = data['schoolnumber']
                            key_month = str(data.get('month', '1'))
                        
                        # 检查是否符合查询条件
                        if name and data['name'] != name:
                            continue
                        if schoolnumber and key_schoolnumber != schoolnumber:
                            continue
                        if month and int(key_month) != month:
                            continue
                
                        # 显示符合条件的记录
                        found = True
                        self.studentdata.insert(tk.END, 
                            f"{data['schoolnumber']}\t{data['name']}\t{data.get('chinese', 'NA')}\t{data.get('math', 'NA')}\t"
                            f"{data.get('english', 'NA')}\t{data.get('physics', 'NA')}\t{data.get('chemistry', 'NA')}\t"
                            f"{data.get('biology', 'NA')}\t{data.get('total', 'NA')}\t{data.get('month', 'NA')}\n", 'data_tag')
                        self.studentdata.tag_config('data_tag', foreground='#b0bec5', font=('Consolas', 12))
                    except (json.JSONDecodeError, KeyError, ValueError) as e:
                        continue
            except Exception as e:
                messagebox.showerror('错误', f'查询过程中发生错误: {str(e)}')
                return
            
            # 清空输入框
            for entry in [self.entry1, self.entry5, self.entry6]:
                entry.delete(0, tk.END)
            
            if found:
                messagebox.showinfo('提示', '查询成功')
            else:
                messagebox.showinfo('提示', '未找到符合条件的数据')

        if self.status_a:
            self.status_a = 0
            errors = []
            try:
                num4 = self.entry5.get().strip()
                num5 = self.entry6.get().strip()
                reply = self.entry1.get().strip()
                num1 = self.entry2.get().strip()
                num2 = self.entry3.get().strip()
                num3 = self.entry4.get().strip()
                num6 = self.entry7.get().strip()
                num7 = self.entry8.get().strip()
                num8 = self.entry9.get().strip()
                
                if not num4.isdigit():
                    errors.append("学号必须是数字")
                if not reply:
                    errors.append("姓名不能为空")
                if not num5.isdigit() or not 1 <= int(num5) <= 12:
                    errors.append("月份必须是1到12之间的整数")
                
                scores = [num1, num2, num3, num6, num7, num8]
                subjects = ["语文", "数学", "英语", "物理", "化学", "生物"]
                score_keys = ["chinese", "math", "english", "physics", "chemistry", "biology"]
                
                student_score_data = {}
                for score_str, subject_name, score_key in zip(scores, subjects, score_keys):
                    if score_str:
                        if not score_str.isdigit() or not 0 <= int(score_str) <= 100:
                            errors.append(f"{subject_name}成绩必须为空或在0到100之间")
                        student_score_data[score_key] = int(score_str)
                    else:
                        student_score_data[score_key] = None
                
                if errors:
                    raise ValueError

                student_data = {
                    'schoolnumber': num4, 'name': reply,
                    **student_score_data,
                    'month': int(num5)
                }
                
                total = sum(filter(None, student_score_data.values()))
                student_data['total'] = total if total > 0 else None
                
                key = f"{num4}_{num5}"

                if self.db0.hexists('student', key):
                    messagebox.showwarning('警告', f'{num5}月份学号{num4}的记录已存在，请勿重复创建。如需修改请使用修改功能。')
                    return
                
                self.db0.hset('student', key, json.dumps(student_data))
                self.data0 = self.db0.hgetall('student')
                
                messagebox.showinfo('提示', f'新建学生数据成功，数据成功保存到（{num5}月）数据库。')
                
            except ValueError:
                error_message = "\n".join(errors) if errors else "输入数据不合法，请检查并重新输入！"
                messagebox.showerror('错误', error_message)
            except Exception as e:
                messagebox.showerror('错误', f'处理过程中发生错误: {str(e)}')
            
            finally:
                for entry in [self.entry1, self.entry2, self.entry3, self.entry4, self.entry5, self.entry6, self.entry7, self.entry8, self.entry9]:
                    entry.delete(0, tk.END)

        if self.status_b:
            self.status_b = 0
            pass

        if self.status_c:
            self.status_c = 0
            schoolnumber = self.entry5.get().strip()
            try:
                month_str = self.entry6.get().strip()
                month = int(month_str) if month_str else None
                if month is not None and not (1 <= month <= 12):
                    messagebox.showinfo('提示', '月份输入不符合要求，请输入1-12之间的数字或留空删除所有月份')
                    return
            except ValueError:
                messagebox.showinfo('提示', '月份必须是数字')
                return

            if not schoolnumber and month is None:
                messagebox.showinfo('提示', '请至少输入学号或月份来指定删除条件')
                return

            keys_to_delete = []
            for key, value in list(self.data0.items()):
                try:
                    data = json.loads(value)
                    
                    key_schoolnumber, key_month_str = key.split('_')
                    key_month = int(key_month_str) if key_month_str else None

                    match_schoolnumber = (not schoolnumber) or (key_schoolnumber == schoolnumber)
                    match_month = (month is None) or (key_month == month)

                    if match_schoolnumber and match_month:
                        keys_to_delete.append(key)
                except (json.JSONDecodeError, KeyError, ValueError):
                    continue

            if keys_to_delete:
                confirmed = messagebox.askyesno("确认删除", f"确定要删除以下 {len(keys_to_delete)} 条记录吗?\n{' '.join(keys_to_delete)}")
                if confirmed:
                    for key in keys_to_delete:
                        self.db0.hdel('student', key)
                        if '_' in key:
                            current_schoolnumber = key.split('_')[0]
                        else:
                            try:
                                data = json.loads(self.data0.get(key, '{}'))
                                current_schoolnumber = data.get('schoolnumber')
                            except:
                                current_schoolnumber = None

                        has_other_months = False
                        if current_schoolnumber:
                            for other_key in self.data0.keys():
                                if other_key.startswith(f"{current_schoolnumber}_") and other_key != key:
                                    has_other_months = True
                                    break
                            if not has_other_months:
                                self.db1.delete(current_schoolnumber)

                    self.data0 = self.db0.hgetall('student')
                    messagebox.showinfo('提示', f'成功删除 {len(keys_to_delete)} 条记录，数据已同步到数据库。')
                else:
                    messagebox.showinfo('提示', '删除操作已取消。')
            else:
                messagebox.showinfo('提示', '未找到符合删除条件的数据。')
            
            for entry in [self.entry1, self.entry5, self.entry6]:
                entry.delete(0, tk.END)

        if self.status_d:
            self.status_d = 0
            schoolnumber = self.entry5.get().strip()
            try:
                month_str = self.entry6.get().strip()
                month = int(month_str)
                if not (1 <= month <= 12):
                    messagebox.showinfo('提示', '月份必须在1-12之间')
                    return
            except ValueError:
                messagebox.showinfo('提示', '请输入有效的学号和月份')
                return

            if not schoolnumber:
                messagebox.showinfo('提示', '请输入学号')
                return

            composite_key = f'{schoolnumber}_{month}'

            if composite_key not in self.data0:
                messagebox.showinfo('提示', f'不存在{month}月份学号为{schoolnumber}的记录')
                return

            try:
                name = self.entry1.get().strip()
                chinese_str = self.entry2.get().strip()
                math_str = self.entry3.get().strip()
                english_str = self.entry4.get().strip()
                physics_str = self.entry7.get().strip()
                chemistry_str = self.entry8.get().strip()
                biology_str = self.entry9.get().strip()

                scores_input = {
                    'chinese': chinese_str, 'math': math_str, 'english': english_str,
                    'physics': physics_str, 'chemistry': chemistry_str, 'biology': biology_str
                }
                updated_scores = {}
                errors = []

                for subject, score_str in scores_input.items():
                    if score_str:
                        if not score_str.isdigit() or not (0 <= int(score_str) <= 100):
                            errors.append(f"{subject}分数必须为空或在0-100之间")
                        else:
                            updated_scores[subject] = int(score_str)
                    else:
                        updated_scores[subject] = None

                if errors:
                    messagebox.showinfo('提示', "\n".join(errors))
                    return

                existing_data = json.loads(self.data0[composite_key])

                student_data = existing_data.copy()
                student_data['schoolnumber'] = schoolnumber
                student_data['month'] = month

                if name:
                    student_data['name'] = name

                student_data.update(updated_scores)

                subject_keys = ["chinese", "math", "english", "physics", "chemistry", "biology"]
                total = sum(filter(None, [student_data.get(subj, None) for subj in subject_keys]))
                student_data['total'] = total if total > 0 else None

                self.db0.hset('student', composite_key, json.dumps(student_data))
                self.data0 = self.db0.hgetall('student')
                messagebox.showinfo('提示', '修改学生数据成功')

            except ValueError:
                messagebox.showerror('错误', '输入数据格式错误，请检查学号、月份和成绩是否为有效数字。')
            except Exception as e:
                messagebox.showerror('错误', f'修改过程中发生错误: {str(e)}')

            finally:
                for entry in [self.entry1, self.entry2, self.entry3, self.entry4,
                             self.entry5, self.entry6, self.entry7, self.entry8, self.entry9]:
                    entry.delete(0, tk.END)

        if self.status_e:
            self.status_e = 0
            pass

    def create_data(self):
        self.get_next2()
        self.status_a = 1
        for entry in [self.entry1, self.entry2, self.entry3, self.entry4, self.entry5, self.entry6, self.entry7, self.entry8, self.entry9]:
            entry.delete(0, tk.END)

    def show_data(self):
        self.acquire_data()

    def acquire_data(self):
        self.studentdata.delete('1.0', 'end')
        self.str3 = """
        =====================================
          请输入查询条件 (可组合):
          - 学号
          - 姓名
          - 月份 (1-12)
        =====================================
           填写后点击上方【信息确定】按钮
        =====================================
        """
        self.studentdata.insert(tk.END, self.str3, 'guide_tag')
        self.studentdata.tag_config('guide_tag', foreground='#b0bec5', font=('Consolas', 12))
        self.status_acq = 1
        for entry in [self.entry1, self.entry5, self.entry6]:
            entry.delete(0, tk.END)

    def delete_data(self):
        self.studentdata.delete('0.0', 'end')
        self.str4 = """
        =====================================
          请输入要删除的学生的 学号 和 月份
          - 仅输入学号则删除该学生所有月份记录
          - 同时输入学号和月份则删除指定记录
        =====================================
           填写后点击上方【信息确定】按钮
        =====================================
        """
        self.studentdata.insert(tk.END, self.str4, 'guide_tag')
        self.studentdata.tag_config('guide_tag', foreground='#b0bec5', font=('Consolas', 12))
        self.status_c = 1
        for entry in [self.entry5, self.entry6]:
            entry.delete(0, tk.END)
        self.entry1.delete(0, tk.END)

    def modify_data(self):
        self.studentdata.delete('0.0', 'end')
        self.str5 = """
        =====================================
           请输入要修改学生的 学号 和 月份 (必须)
           输入框中填写要修改的字段新值 (可部分填写)
        =====================================
           填写后点击上方【信息确定】按钮
        =====================================
        """
        self.studentdata.insert(tk.END, self.str5, 'guide_tag')
        self.studentdata.tag_config('guide_tag', foreground='#b0bec5', font=('Consolas', 12))
        self.status_d = 1
        for entry in [self.entry1, self.entry2, self.entry3, self.entry4, self.entry5, self.entry6, self.entry7, self.entry8, self.entry9]:
            entry.delete(0, tk.END)

    def show_analysis_guide(self):
        self.studentdata.delete('1.0', 'end')
        guide = """
        =====================================
                使用 AI 分析功能步骤：
        =====================================
        1. 在【学号】输入框中输入要分析学生的学号
        2. 点击下方的【确认查找】按钮获取数据
        3. 数据加载后，按钮会变为【AI分析】，点击进行分析
        =====================================
        """
        self.studentdata.insert(tk.END, guide, 'guide_tag')
        self.studentdata.tag_config('guide_tag', foreground='#b0bec5', font=('Consolas', 12))
        
        try:
            self.confirm_analysis_button.configure(
                text='确认查找',
                font=('微软雅黑', 12, 'bold'),
                bg='#00bcd4',
                fg='#121212',
                activebackground='#00838f',
                activeforeground='#ffffff',
                relief='flat',
                padx=10, pady=5,
                command=self.perform_analysis
            )
        except AttributeError:
            self.confirm_analysis_button = tk.Button(
                self.main_frame,
                text='确认查找',
                font=('微软雅黑', 12, 'bold'),
                bg='#00bcd4',
                fg='#121212',
                activebackground='#00838f',
                activeforeground='#ffffff',
                relief='flat',
                padx=10, pady=5,
                command=self.perform_analysis
            )
            self.confirm_analysis_button.pack(pady=10, padx=20, anchor='e')

    def perform_analysis(self):
        schoolnumber = self.entry5.get().strip()
        if not schoolnumber:
            messagebox.showinfo('提示', '请先输入要分析的学生学号')
            return

        student_data = []
        for key, value in self.data0.items():
            try:
                if '_' in key:
                    key_schoolnumber, key_month_str = key.split('_')
                    if key_schoolnumber == schoolnumber:
                        data = json.loads(value)
                        student_data.append(data)
            except json.JSONDecodeError:
                continue

        if not student_data:
            messagebox.showinfo('提示', '未找到该学生的成绩数据')
            self.confirm_analysis_button.configure(text='确认查找', command=self.perform_analysis)
            return

        student_data.sort(key=lambda x: x.get('month', 0))

        self.studentdata.delete('1.0', 'end')
        self.studentdata.insert(tk.END, f"学生 {student_data[0].get('name', '未知')} 的成绩数据：\n\n", 'info_tag')
        self.studentdata.tag_config('info_tag', foreground='#00bcd4', font=('微软雅黑', 12, 'bold'))

        for data in student_data:
            month_text = f"第{data.get('month', '未知')}月成绩\n"
            self.studentdata.insert(tk.END, month_text, 'month_header_tag')
            self.studentdata.tag_config('month_header_tag', foreground='#81d4fa', font=('Consolas', 12, 'italic'))

            scores_text = f"语文：{data.get('chinese', 'NA')} 数学：{data.get('math', 'NA')} 英语：{data.get('english', 'NA')}\n物理：{data.get('physics', 'NA')} 化学：{data.get('chemistry', 'NA')} 生物：{data.get('biology', 'NA')}\n总分：{data.get('total', 'NA')}\n\n"
            self.studentdata.insert(tk.END, scores_text, 'score_data_tag')
            self.studentdata.tag_config('score_data_tag', foreground='#b0bec5', font=('Consolas', 12))

        self.confirm_analysis_button.configure(
            text='AI分析',
            bg='#e91e63',
            fg='#121212',
            activebackground='#c2185b',
            activeforeground='#ffffff',
            command=lambda: self.ai_analyze_data(student_data)
        )

    def update_loading_status(self):
        dots = ['.', '..', '...', '....', '.....', '......']
        current_text = self.studentdata.get('1.0', tk.END).strip()
        base_text = current_text.split('\n\n正在进行智能分析')[0]
        
        i = 0
        while hasattr(self, 'is_analyzing') and self.is_analyzing:
            full_text = self.studentdata.get('1.0', tk.END).strip()
            analysis_marker = "AI分析结果："
            marker_index = full_text.find(analysis_marker)

            if marker_index != -1:
                display_text = full_text[:marker_index] + f'\n\n正在进行智能分析{dots[i]}' + full_text[marker_index:]
            else:
                if '\n\n正在进行智能分析' in full_text:
                    lines = full_text.split('\n')
                    for j in range(len(lines)):
                        if '正在进行智能分析' in lines[j]:
                            lines[j] = f'正在进行智能分析{dots[i]}'
                            break
                    display_text = '\n'.join(lines)
                else:
                    display_text = full_text + f'\n\n正在进行智能分析{dots[i]}'

            self.studentdata.delete('1.0', tk.END)
            self.studentdata.insert(tk.END, display_text, 'loading_tag')
            self.studentdata.tag_config('loading_tag', foreground='#ffc107', font=('Consolas', 12, 'italic'))

            i = (i + 1) % len(dots)
            time.sleep(0.5)

        if not self.is_analyzing:
            full_text = self.studentdata.get('1.0', tk.END).strip()
            if '\n\n正在进行智能分析' in full_text:
                lines = full_text.split('\n')
                display_lines = [line for line in lines if '正在进行智能分析' not in line]
                final_text = '\n'.join(display_lines)
                self.studentdata.delete('1.0', tk.END)
                self.studentdata.insert(tk.END, final_text)

    def ai_analyze_data(self, student_data):
        self.confirm_analysis_button.configure(
            text='正在分析...',
            bg='#607d8b',
            fg='#121212',
            activebackground='#546e7a',
            activeforeground='#ffffff',
            state=tk.DISABLED
        )
        for entry in [self.entry1, self.entry5, self.entry6]:
            entry.delete(0, tk.END)

        def analysis_thread():
            try:
                prompt = f"根据以下学生 {student_data[0].get('name', '未知')} 的成绩数据，请提供简洁的智能分析和具体的学习建议。数据格式为：月份：科目1成绩, 科目2成绩,... 总分。\n\n"
                
                for data in student_data:
                    prompt += f"第{data.get('month', '未知')}月：语文{data.get('chinese', 'NA')}，数学{data.get('math', 'NA')}，英语{data.get('english', 'NA')}，"
                    prompt += f"物理{data.get('physics', 'NA')}，化学{data.get('chemistry', 'NA')}，生物{data.get('biology', 'NA')}，总分{data.get('total', 'NA')}\n"

                prompt += "\n请简洁分析：\n1. 成绩整体变化趋势\n2. 优势与劣势学科分析\n3. 针对性学习建议\n4. 如何有效提升弱势科目成绩\n\n请直接给出分析结果，不要包含额外的引导语或 Markdown 格式。"

                response = openai.ChatCompletion.create(
                    model="gpt-4",
                    messages=[
                        {"role": "system", "content": "你是一位简洁高效的教育顾问，专注于成绩分析和学习建议，回答直接、有条理，不使用 Markdown。"},
                        {"role": "user", "content": prompt}
                    ],
                    temperature=0.7,
                    max_tokens=500
                )
                
                analysis = response.choices[0].message.content
                self.root.after_idle(self.update_analysis_result, analysis)
                
            except Exception as e:
                self.root.after_idle(lambda: messagebox.showerror('AI分析失败', f'发生错误：{str(e)}。\n请检查您的API密钥和网络连接。'))
            finally:
                self.is_analyzing = False
                self.root.after_idle(lambda: self.confirm_analysis_button.configure(
                    text='确认查找',
                    bg='#00bcd4',
                    fg='#121212',
                    activebackground='#00838f',
                    activeforeground='#ffffff',
                    state=tk.NORMAL,
                    command=self.perform_analysis
                ))

        self.is_analyzing = True
        analysis_thread = Thread(target=analysis_thread)
        analysis_thread.daemon = True
        analysis_thread.start()

        loading_thread = Thread(target=self.update_loading_status)
        loading_thread.daemon = True
        loading_thread.start()

    def update_analysis_result(self, analysis):
        self.update_loading_status()

        self.studentdata.insert(tk.END, "\n\nAI分析结果：\n\n", 'analysis_header_tag')
        self.studentdata.tag_config('analysis_header_tag', foreground='#e91e63', font=('微软雅黑', 12, 'bold'))

        self.studentdata.insert(tk.END, analysis, 'analysis_text_tag')
        self.studentdata.tag_config('analysis_text_tag', foreground='#b0bec5', font=('Consolas', 12))

    def ai_analysis(self):
        self.show_analysis_guide()
        self.entry5.delete(0, tk.END)
        for entry in [self.entry1, self.entry2, self.entry3, self.entry4, self.entry6, self.entry7, self.entry8, self.entry9]:
            entry.delete(0, tk.END)

    def quit(self):
        self.root.destroy()

if __name__ == '__main__':
    root = tk.Tk()
    StudentManager(root)
    root.mainloop()








